<?php

namespace app\admin\controller;

use app\common\controller\Backend;

class Product extends Backend
{
    //继承父类
    public function __construct()
    {
        parent::__construct();
        $this->ProductModel = model('Product.Product');
        $this->ProductTypeModel = model('Product.ProductType');
    }

    //商品列表页面
    public function productlist()
    {
        $ProductList = null;
        $where = null;
        if ($this->request->isGet()) {
            $params = $this->request->param();
            $search_field = !empty($params['search_field']) ? $params['search_field'] : '';
            $keyword = !empty($params['keyword']) ? $params['keyword'] : '';
            if ($search_field == 'name') {
                $where = "1";
                $ProductList = $this->ProductModel->where('product.name', 'like', "%$keyword%")->order('id dsc')->with('productType')->paginate(7);
            }
            if ($where == null) {
                $ProductList = $this->ProductModel->order('id dsc')->with('productType')->paginate(7);
            }
        }
        // $ProductList = $this->ProductModel->order('id dsc')->with('productType')->paginate(7);
        $navTitle = '商品管理';
        $navSmall = '商品列表';
        return $this->fetch('', [
            'navTitle' => $navTitle,
            'navSmall' => $navSmall,
            'productList' => $ProductList
        ]);
    }

    //商品添加页面
    public function productadd()
    {
        if ($this->request->isPost()) {
            $params = $this->request->param();
            //封装数据
            $productData = [
                'name' => $params['name'],
                'typeid' => $params['typeid'],
                'price' => $params['price'],
                'stock' => $params['stock'],
                'flag' => $params['flag'],
                'content' => $params['content'],
            ];
            $FilesList = null;
            //多图上传
            //图片上传数据
            if (isset($_FILES['thumbs']) && $_FILES['thumbs']['size'][0] > 0) {
                $file = uploadMore('thumbs');
                if (!$file) {
                    $this->error('图片上传失败');
                }
                $FilesList = $file['data'];
                $lenFiles = count((array)$file['data']);
                $strFiles = '[';
                foreach ((array)$file['data'] as $item => $val) {
                    if ($lenFiles == $item + 1) {
                        $strFiles .= "\"" . $val . "\"";
                    } else {
                        $strFiles .= "\"" . $val . "\",";
                    }
                }
                $strFiles .= ']';
                $productData['thumbs'] = $strFiles;
            }

            $result = $this->ProductModel->validate('common/Product/Product')->save($productData);
            // $result = FALSE;
            if ($result === FALSE) {
                if (isset($_FILES['thumbs']) && $_FILES['thumbs']['size'][0] > 0) {
                    foreach ((array)$FilesList as $item => $val) {
                        // echo $val;
                        @is_file('./' . $val) && @unlink('./' . $val);
                    }
                }
                $this->error($this->ProductModel->getError());
            } else {
                $this->success('新增商品成功', url('admin/product/productlist'));
            }
        }
        $productTypeList = $this->ProductTypeModel->select();
        $navTitle = '商品管理';
        $navSmall = '商品列表';
        return $this->fetch('', [
            'navTitle' => $navTitle,
            'navSmall' => $navSmall,
            'productTypeList' => $productTypeList
        ]);
    }

    //商品编辑页面 
    public function productedit()
    {
        $productId = $this->request->param('productId', 0);
        $productList = $this->ProductModel->find($productId);

        //处理更新提交过来的数据
        if ($this->request->isPost()) {
            $params = $this->request->param();
            //封装数据
            $productData = [
                'id' => $productId,
                'name' => $params['name'],
                'typeid' => $params['typeid'],
                'price' => $params['price'],
                'stock' => $params['stock'],
                'flag' => $params['flag'],
                'content' => $params['content'],
            ];
            $FilesList = null;
            //多图上传
            //图片上传数据
            if (isset($_FILES['thumbs']) && $_FILES['thumbs']['size'][0] > 0) {
                $file = uploadMore('thumbs');
                if (!$file) {
                    $this->error('图片上传失败');
                }
                $FilesList = $file['data'];
                $lenFiles = count((array)$file['data']);
                $strFiles = '[';
                foreach ((array)$file['data'] as $item => $val) {
                    if ($lenFiles == $item + 1) {
                        $strFiles .= "\"" . $val . "\"";
                    } else {
                        $strFiles .= "\"" . $val . "\",";
                    }
                }
                $strFiles .= ']';
                $productData['thumbs'] = $strFiles;
            } else {
                $productData['thumbs'] = $productList['thumbs'];
            }

            $result = $this->ProductModel->validate('common/Product/Product')->isUpdate(true)->save($productData);
            // $result = FALSE;
            if ($result === FALSE) {
                if (isset($_FILES['thumbs']) && $_FILES['thumbs']['size'][0] > 0) {
                    foreach ((array)$FilesList as $item => $val) {
                        // echo $val;
                        @is_file('./' . $val) && @unlink('./' . $val);
                    }
                }
                $this->error($this->ProductModel->getError());
            } else {
                if (isset($_FILES['thumbs']) && $_FILES['thumbs']['size'][0] > 0) {
                    foreach (json_decode($productList['thumbs']) as $itemTwo => $val) {
                        if (!empty($val)) {
                            @is_file('./' . $val) && @unlink('./' . $val);
                        }
                    }
                }
                $this->success('新增商品成功', url('admin/product/productlist'));
            }
        }

        if ($productId == 0 || !$productList) {
            $this->error('该商品不存在');
        }

        $productTypeList = $this->ProductTypeModel->select();
        $navTitle = '商品管理';
        $navSmall = '商品列表';
        return $this->fetch('', [
            'navTitle' => $navTitle,
            'navSmall' => $navSmall,
            'productTypeList' => $productTypeList,
            'productList' => $productList,
        ]);
    }

    //商品回收站
    public function recyclebin()
    {
        //恢复用户数据
        if ($this->request->isPost() && $this->request->isAjax()) {
            $action = $this->request->param('action', '');
            if ($action == 'restore') {
                $list = $this->request->param();
                $deletetimeList =  $this->ProductModel->onlyTrashed()->select($list['list']);
                $result = null;
                foreach ($deletetimeList as $key => $item) {
                    $result = $this->ProductModel->update(['id' => $item['id'], 'deletetime' => null]);
                }

                if ($result === FALSE) {
                    $this->error($this->ProductModel->getError());
                } else {
                    $this->success('恢复成功');
                }
            }
        }

        $productList = null;
        $where = null;
        if ($this->request->isGet()) {
            $params = $this->request->param();
            $search_field = !empty($params['search_field']) ? $params['search_field'] : '';
            $keyword = !empty($params['keyword']) ? $params['keyword'] : '';
            if ($search_field == 'name') {
                $where = "1";
                $productList = $this->ProductModel->where('name', 'like', "%$keyword%")->onlyTrashed()->paginate(7);
            }
            if ($where == null) {
                $productList = $this->ProductModel->onlyTrashed()->paginate(7);
            }
        }

        // $productList = $this->ProductModel->onlyTrashed()->paginate(7);
        $navTitle = '商品管理';
        $navSmall = '商品列表';
        return $this->fetch('', [
            'navTitle' => $navTitle,
            'navSmall' => $navSmall,
            'productList' => $productList,
        ]);
    }

    //商品删除
    public function productdel()
    {
        $action = $this->request->param('action', '');
        $result = null;
        //商品单选普通删除
        if ($action == 'productDel') {
            $id = $this->request->param('id', 0);
            $result = $this->ProductModel->destroy($id);
        }
        //商品多选普通删除
        if ($action == 'productDelAll') {
            $list = $this->request->param();
            $result = $this->ProductModel->destroy($list['list']);
        }
        //商品单选永久删除
        if ($action == 'PMDel') {
            $id = $this->request->param('id', 0);
            // 删除图片数据
            $thumbs = $this->ProductModel->withTrashed()->find($id);
            foreach (json_decode($thumbs['thumbs']) as $item => $val) {
                if (!empty($val)) {
                    @is_file('./' . $val) && @unlink('./' . $val);
                }
            }
            $result = $this->ProductModel->destroy($id, true);
        }
        //商品多选永久删除
        if ($action == 'PMDelAll') {
            $list = $this->request->param();
            // 删除多选图片数据
            foreach ($list['list'] as $item => $val) {
                $thumbs = $this->ProductModel->withTrashed()->find($val);
                foreach (json_decode($thumbs['thumbs']) as $itemTwo => $valTwo) {
                    if (!empty($valTwo)) {
                        @is_file('./' . $valTwo) && @unlink('./' . $valTwo);
                    }
                }
            }
            $result = $this->ProductModel->destroy($list['list'], true);
        }
        if ($result === FALSE) {
            $this->error($this->ProductModel->getError());
        } else {
            $this->success('删除成功');
        }
    }

    //商品分类页面
    public function productsort()
    {
        $productSortlist =  $this->ProductTypeModel->order('weigh desc')->paginate(9);
        $navTitle = '商品管理';
        $navSmall = '商品分类';
        return $this->fetch('', [
            'navTitle' => $navTitle,
            'navSmall' => $navSmall,
            "productSortlist" => $productSortlist
        ]);
    }

    //商品分类添加
    public function productsortadd()
    {
        if ($this->request->isPost() && $this->request->isAjax()) {
            $action = $this->request->param('action');
            if ($action === 'name') {
                $name = $this->request->param('name');
                $nameResult = $this->ProductTypeModel->where('name', $name)->find();
                if ($nameResult) {
                    $this->error('商品分类名称已存在');
                } else {
                    $this->success('商品分类名称可以使用');
                }
            }
        } else if ($this->request->isPost()) {
            $params = $this->request->param();

            //封装数据
            $productTypeData = [
                'name' => $params['name'],
                'weigh' => $params['weigh']
            ];

            if (!empty($_FILES)) {
                $file = upload('cover');
                if (!$file) {
                    $this->error('图片上传失败');
                }
                $productTypeData['cover'] = $file['data'];
            }
            $result = $this->ProductTypeModel->validate('common/Product/ProductType')->save($productTypeData);
            // $result = FALSE;
            if ($result === FALSE) {
                if (!empty($_FILES)) {
                    // echo $productTypeData['cover'];
                    @is_file('.' . $productTypeData['cover']) && @unlink('.' . $productTypeData['cover']);
                }
                $this->error($this->ProductTypeModel->getError());
            } else {
                $this->success('添加商品分类成功', url('admin/product/productsort'));
            }
        }
        $navTitle = '商品管理';
        $navSmall = '商品分类';
        return $this->fetch('', [
            'navTitle' => $navTitle,
            'navSmall' => $navSmall
        ]);
    }

    //商品分类编辑
    public function productsortedit()
    {
        $id = $this->request->param('id', 0);
        $ProductType = $this->ProductTypeModel->find($id);
        if ($this->request->isPost()) {
            $params = $this->request->param();
            //封装数据
            $productTypeData = [
                'id' => $id,
                'name' => $params['name'],
                'weigh' => $params['weigh']
            ];
            $ProductType = $this->ProductTypeModel->find($this->request->param('id', 0));
            if (!empty($_FILES['cover']['name'])) {
                $file = upload('cover');
                if (!$file) {
                    $this->error('图片上传失败');
                }
                $productTypeData['cover'] = $file['data'];
            } else {
                $productTypeData['cover'] = $ProductType['cover'];
            }

            $result = $this->ProductTypeModel->validate('common/Product/ProductType')->isUpdate(true)->save($productTypeData);

            if ($result === FALSE) {
                if (!empty($_FILES['cover']['name'])) {
                    @is_file('.' . $productTypeData['cover']) && @unlink('.' . $productTypeData['cover']);
                }
                $this->error($this->ProductTypeModel->getError());
            } else {
                if (!empty($_FILES['cover']['name'])) {
                    @is_file('.' . $ProductType['cover']) && @unlink('.' . $ProductType['cover']);
                }
                $this->success('更新商品分类成功', url('admin/product/productsort'));
            }
        }
        $navTitle = '商品管理';
        $navSmall = '商品分类';
        return $this->fetch('', [
            'navTitle' => $navTitle,
            'navSmall' => $navSmall,
            'ProductType' => $ProductType
        ]);
    }

    //商品分类删除
    public function sortdel()
    {
        $action = $this->request->param('action', '');
        $result = null;
        //商品分类单选永久删除
        if ($action == 'sortDel') {
            $id = $this->request->param('id', 0);
            //单选删除图片
            $cover = $this->ProductTypeModel->where('id', $id)->value('cover');
            if (!empty($cover)) {
                @is_file('.' . $cover) && @unlink('.' . $cover);
            }
            $result = $this->ProductTypeModel->destroy($id, true);
        }
        //商品分类多选永久删除
        if ($action == 'sortDelAll') {
            $list = $this->request->param();
            //批量删除图片
            foreach ($list['list'] as $item => $val) {
                $cover = $this->ProductTypeModel->where('id', $val)->value('cover');
                if (!empty($cover)) {
                    @is_file('.' . $cover) && @unlink('.' . $cover);
                }
            }
            $result = $this->ProductTypeModel->destroy($list['list']);
        }
        if ($result === FALSE) {
            $this->error($this->ProductTypeModel->getError());
        } else {
            $this->success('删除成功', url('admin/product/productsort'));
        }
    }
}
